package cn.tedu.lucky.draw.server.controller;

import cn.tedu.lucky.draw.server.common.annotation.OperationLog;
import cn.tedu.lucky.draw.server.common.result.JsonResult;
import cn.tedu.lucky.draw.server.protocol.po.Activity;
import cn.tedu.lucky.draw.server.protocol.po.Prize;
import cn.tedu.lucky.draw.server.protocol.query.ActivityQuery;
import cn.tedu.lucky.draw.server.service.IActivityService;
import org.json.JSONException;
import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    @PostMapping("/draw/activity/getAll")
    public JsonResult<List<Activity>> getAll(@RequestBody ActivityQuery activityQuery){

        List<Activity> activityList=activityService.findAll(activityQuery);
        return JsonResult.ok(activityList);
    }

    @OperationLog(operation = "创建活动")
    @PostMapping("/draw/activity/save")
    public JsonResult save(@RequestBody Activity activity){

        activityService.save(activity);
        return JsonResult.ok();
    }

    @PostMapping("/draw/activity/{id}")
    public JsonResult<Activity> getActivityById(@PathVariable Long id){
        Activity activity=activityService.getActivityById(id);
        return JsonResult.ok(activity);
    }

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job csvToDBJob;

    @Autowired
    private JobExplorer jobExplorer;

    @GetMapping("/activity/csvToDB")
    public String csvToDB() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        JobParameters jobParameters = new JobParametersBuilder(new JobParameters(),jobExplorer)
                .getNextJobParameters(csvToDBJob)
                .toJobParameters();
        JobExecution run = jobLauncher.run(csvToDBJob, jobParameters);
        return run.getId().toString();
    }

    @PostMapping("/app/draw/activity/getAll")
    public JsonResult<List<Activity>> getAll(){
        return JsonResult.ok(activityService.findAll());
    }

    @GetMapping("/app/draw/activity/trigger")
    public JsonResult<Prize> trigger(Long activityId) throws JSONException {
        return JsonResult.ok(activityService.trigger(activityId));
    }
}
